home *** CD-ROM | disk | FTP | other *** search
/ Disc to the Future 2 / Disc to the Future Part II Programmer's Reference (Wayzata Technology)(6013)(1992).bin / MAC / THINKC / 4_0 / LZW_SOUR.CE < prev    next >
Text File  |  1970-01-01  |  44KB  |  1,399 lines

  1. #include <stdio.h>
  2. #define    USERMEM    70000
  3. /* 
  4.  * Compress - data compression program 
  5.  */
  6. #define min(a,b)        ((a>b) ? b : a)
  7.  
  8. /*
  9.  * machine variants which require cc -Dmachine:  pdp11, z8000, pcxt
  10.  */
  11.  
  12. /*
  13.  * Set USERMEM to the maximum amount of physical user memory available
  14.  * in bytes.  USERMEM is used to determine the maximum BITS that can be used
  15.  * for compression.
  16.  *
  17.  * SACREDMEM is the amount of physical memory saved for others; compress
  18.  * will hog the rest.
  19.  */
  20. #ifndef SACREDMEM
  21. #define SACREDMEM       0
  22. #endif
  23.  
  24. #ifndef USERMEM
  25. # define USERMEM        450000  /* default user memory */
  26. #endif
  27.  
  28. #ifdef interdata                /* (Perkin-Elmer) */
  29. #define SIGNED_COMPARE_SLOW     /* signed compare is slower than unsigned */
  30. #endif
  31.  
  32. #ifdef pdp11
  33. # define BITS   12      /* max bits/code for 16-bit machine */
  34. # define NO_UCHAR       /* also if "unsigned char" functions as signed char */
  35. # undef USERMEM 
  36. #endif /* pdp11 */      /* don't forget to compile with -i */
  37.  
  38. #ifdef z8000
  39. # define BITS   12
  40. # undef vax             /* weird preprocessor */
  41. # undef USERMEM 
  42. #endif /* z8000 */
  43.  
  44. #ifdef pcxt
  45. # define BITS   12
  46. # undef USERMEM
  47. #endif /* pcxt */
  48.  
  49. #ifdef USERMEM
  50. # if USERMEM >= (433484+SACREDMEM)
  51. #  define PBITS 16
  52. # else
  53. #  if USERMEM >= (229600+SACREDMEM)
  54. #   define PBITS        15
  55. #  else
  56. #   if USERMEM >= (127536+SACREDMEM)
  57. #    define PBITS       14
  58. #   else
  59. #    if USERMEM >= (73464+SACREDMEM)
  60. #     define PBITS      13
  61. #    else
  62. #     define PBITS      12
  63. #    endif
  64. #   endif
  65. #  endif
  66. # endif
  67. # undef USERMEM
  68. #endif /* USERMEM */
  69.  
  70. #ifdef PBITS            /* Preferred BITS for this memory size */
  71. # ifndef BITS
  72. #  define BITS PBITS
  73. # endif BITS
  74. #endif /* PBITS */
  75.  
  76. #if BITS == 16
  77. # define HSIZE  69001           /* 95% occupancy */
  78. #endif
  79. #if BITS == 15
  80. # define HSIZE  35023           /* 94% occupancy */
  81. #endif
  82. #if BITS == 14
  83. # define HSIZE  18013           /* 91% occupancy */
  84. #endif
  85. #if BITS == 13
  86. # define HSIZE  9001            /* 91% occupancy */
  87. #endif
  88. #if BITS <= 12
  89. # define HSIZE  5003            /* 80% occupancy */
  90. #endif
  91.  
  92. #ifdef M_XENIX                  /* Stupid compiler can't handle arrays with */
  93. # if BITS == 16                 /* more than 65535 bytes - so we fake it */
  94. #  define XENIX_16
  95. # else
  96. #  if BITS > 13                 /* Code only handles BITS = 12, 13, or 16 */
  97. #   define BITS 13
  98. #  endif
  99. # endif
  100. #endif
  101.  
  102. /*
  103.  * a code_int must be able to hold 2**BITS values of type int, and also -1
  104.  */
  105. #if BITS > 15
  106. typedef long int        code_int;
  107. #else
  108. typedef int             code_int;
  109. #endif
  110.  
  111. #ifdef SIGNED_COMPARE_SLOW
  112. typedef unsigned long int count_int;
  113. typedef unsigned short int count_short;
  114. #else
  115. typedef long int          count_int;
  116. #endif
  117.  
  118. #ifdef NO_UCHAR
  119.  typedef char   char_type;
  120. #else
  121.  typedef        unsigned char   char_type;
  122. #endif /* UCHAR */
  123. char_type magic_header[] =  "\037\235" ;      /* 1F 9D */
  124.  
  125. /* Defines for third byte of header */
  126. #define BIT_MASK        0x1f
  127. #define BLOCK_MASK      0x80
  128. /* Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
  129.    a fourth header byte (for expansion).
  130. */
  131. #define INIT_BITS 9                     /* initial number of bits/code */
  132.  
  133. /*
  134.  * compress.c - File compression ala IEEE Computer, June 1984.
  135.  *
  136.  * Authors:     Spencer W. Thomas       (decvax!harpo!utah-cs!utah-gr!thomas)
  137.  *              Jim McKie               (decvax!mcvax!jim)
  138.  *              Steve Davies            (decvax!vax135!petsd!peora!srd)
  139.  *              Ken Turkowski           (decvax!decwrl!turtlevax!ken)
  140.  *              James A. Woods          (decvax!ihnp4!ames!jaw)
  141.  *              Joe Orost               (decvax!vax135!petsd!joe)
  142.  *
  143.  * $Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $
  144.  * $Log:        compress.c,v $
  145.  * Revision 4.0  85/07/30  12:50:00  joe
  146.  * Removed ferror() calls in output routine on every output except first.
  147.  * Prepared for release to the world.
  148.  * 
  149.  * Revision 3.6  85/07/04  01:22:21  joe
  150.  * Remove much wasted storage by overlaying hash table with the tables
  151.  * used by decompress: tab_suffix[1<<BITS], stack[8000].  Updated USERMEM
  152.  * computations.  Fixed dump_tab() DEBUG routine.
  153.  *
  154.  * Revision 3.5  85/06/30  20:47:21  jaw
  155.  * Change hash function to use exclusive-or.  Rip out hash cache.  These
  156.  * speedups render the megamemory version defunct, for now.  Make decoder
  157.  * stack global.  Parts of the RCS trunks 2.7, 2.6, and 2.1 no longer apply.
  158.  *
  159.  * Revision 3.4  85/06/27  12:00:00  ken
  160.  * Get rid of all floating-point calculations by doing all compression ratio
  161.  * calculations in fixed point.
  162.  *
  163.  * Revision 3.3  85/06/24  21:53:24  joe
  164.  * Incorporate portability suggestion for M_XENIX.  Got rid of text on #else
  165.  * and #endif lines.  Cleaned up #ifdefs for vax and interdata.
  166.  *
  167.  * Revision 3.2  85/06/06  21:53:24  jaw
  168.  * Incorporate portability suggestions for Z8000, IBM PC/XT from mailing list.
  169.  * Default to "quiet" output (no compression statistics).
  170.  *
  171.  * Revision 3.1  85/05/12  18:56:13  jaw
  172.  * Integrate decompress() stack speedups (from early pointer mods by McKie).
  173.  * Repair multi-file USERMEM gaffe.  Unify 'force' flags to mimic semantics
  174.  * of SVR2 'pack'.  Streamline block-compress table clear logic.  Increase 
  175.  * output byte count by magic number size.
  176.  * 
  177.  * Revision 3.0   84/11/27  11:50:00  petsd!joe
  178.  * Set HSIZE depending on BITS.  Set BITS depending on USERMEM.  Unrolled
  179.  * loops in clear routines.  Added "-C" flag for 2.0 compatibility.  Used
  180.  * unsigned compares on Perkin-Elmer.  Fixed foreground check.
  181.  *
  182.  * Revision 2.7   84/11/16  19:35:39  ames!jaw
  183.  * Cache common hash codes based on input statistics; this improves
  184.  * performance for low-density raster images.  Pass on #ifdef bundle
  185.  * from Turkowski.
  186.  *
  187.  * Revision 2.6   84/11/05  19:18:21  ames!jaw
  188.  * Vary size of hash tables to reduce time for small files.
  189.  * Tune PDP-11 hash function.
  190.  *
  191.  * Revision 2.5   84/10/30  20:15:14  ames!jaw
  192.  * Junk chaining; replace with the simpler (and, on the VAX, faster)
  193.  * double hashing, discussed within.  Make block compression standard.
  194.  *
  195.  * Revision 2.4   84/10/16  11:11:11  ames!jaw
  196.  * Introduce adaptive reset for block compression, to boost the rate
  197.  * another several percent.  (See mailing list notes.)
  198.  *
  199.  * Revision 2.3   84/09/22  22:00:00  petsd!joe
  200.  * Implemented "-B" block compress.  Implemented REVERSE sorting of tab_next.
  201.  * Bug fix for last bits.  Changed fwrite to putchar loop everywhere.
  202.  *
  203.  * Revision 2.2   84/09/18  14:12:21  ames!jaw
  204.  * Fold in news changes, small machine typedef from thomas,
  205.  * #ifdef interdata from joe.
  206.  *
  207.  * Revision 2.1   84/09/10  12:34:56  ames!jaw
  208.  * Configured fast table lookup for 32-bit machines.
  209.  * This cuts user time in half for b <= FBITS, and is useful for news batching
  210.  * from VAX to PDP sites.  Also sped up decompress() [fwrite->putc] and
  211.  * added signal catcher [plus beef in writeerr()] to delete effluvia.
  212.  *
  213.  * Revision 2.0   84/08/28  22:00:00  petsd!joe
  214.  * Add check for foreground before prompting user.  Insert maxbits into
  215.  * compressed file.  Force file being uncompressed to end with ".Z".
  216.  * Added "-c" flag and "zcat".  Prepared for release.
  217.  *
  218.  * Revision 1.10  84/08/24  18:28:00  turtlevax!ken
  219.  * Will only compress regular files (no directories), added a magic number
  220.  * header (plus an undocumented -n flag to handle old files without headers),
  221.  * added -f flag to force overwriting of possibly existing destination file,
  222.  * otherwise the user is prompted for a response.  Will tack on a .Z to a
  223.  * filename if it doesn't have one when decompressing.  Will only replace
  224.  * file if it was compressed.
  225.  *
  226.  * Revision 1.9  84/08/16  17:28:00  turtlevax!ken
  227.  * Removed scanargs(), getopt(), added .Z extension and unlimited number of
  228.  * filenames to compress.  Flags may be clustered (-Ddvb12) or separated
  229.  * (-D -d -v -b 12), or combination thereof.  Modes and other status is
  230.  * copied with copystat().  -O bug for 4.2 seems to have disappeared with
  231.  * 1.8.
  232.  *
  233.  * Revision 1.8  84/08/09  23:15:00  joe
  234.  * Made it compatible with vax version, installed jim's fixes/enhancements
  235.  *
  236.  * Revision 1.6  84/08/01  22:08:00  joe
  237.  * Sped up algorithm significantly by sorting the compress chain.
  238.  *
  239.  * Revision 1.5  84/07/13  13:11:00  srd
  240.  * Added C version of vax asm routines.  Changed structure to arrays to
  241.  * save much memory.  Do unsigned compares where possible (faster on
  242.  * Perkin-Elmer)
  243.  *
  244.  * Revision 1.4  84/07/05  03:11:11  thomas
  245.  * Clean up the code a little and lint it.  (Lint complains about all
  246.  * the regs used in the asm, but I'm not going to "fix" this.)
  247.  *
  248.  * Revision 1.3  84/07/05  02:06:54  thomas
  249.  * Minor fixes.
  250.  *
  251.  * Revision 1.2  84/07/05  00:27:27  thomas
  252.  * Add variable bit length output.
  253.  *
  254.  */
  255. static char rcs_ident[] = "$Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $";
  256.  
  257. #include <stdio.h>
  258. #include <ctype.h>
  259. #include <signal.h>
  260.  
  261. #define ARGVAL() (*++(*argv) || (--argc && *++argv))
  262.  
  263. int n_bits;                             /* number of bits/code */
  264. int maxbits = BITS;                     /* user settable max # bits/code */
  265. code_int maxcode;                       /* maximum code, given n_bits */
  266. code_int maxmaxcode = 1 << BITS;        /* should NEVER generate this code */
  267. #ifdef COMPATIBLE               /* But wrong! */
  268. # define MAXCODE(n_bits)        (1 << (n_bits) - 1)
  269. #else
  270. # define MAXCODE(n_bits)        ((1 << (n_bits)) - 1)
  271. #endif /* COMPATIBLE */
  272.  
  273. #ifdef XENIX_16
  274. count_int htab0[8192];
  275. count_int htab1[8192];
  276. count_int htab2[8192];
  277. count_int htab3[8192];
  278. count_int htab4[8192];
  279. count_int htab5[8192];
  280. count_int htab6[8192];
  281. count_int htab7[8192];
  282. count_int htab8[HSIZE-65536];
  283. count_int * htab[9] = {
  284.         htab0, htab1, htab2, htab3, htab4, htab5, htab6, htab7, htab8 };
  285.  
  286. #define htabof(i)       (htab[(i) >> 13][(i) & 0x1fff])
  287. unsigned short code0tab[16384];
  288. unsigned short code1tab[16384];
  289. unsigned short code2tab[16384];
  290. unsigned short code3tab[16384];
  291. unsigned short code4tab[16384];
  292. unsigned short * codetab[5] = {
  293.         code0tab, code1tab, code2tab, code3tab, code4tab };
  294.  
  295. #define codetabof(i)    (codetab[(i) >> 14][(i) & 0x3fff])
  296.  
  297. #else   /* Normal machine */
  298. count_int *htab;
  299. unsigned short *codetab;
  300. #define htabof(i)       htab[i]
  301. #define codetabof(i)    codetab[i]
  302. #endif  /* XENIX_16 */
  303. code_int hsize = HSIZE;                 /* for dynamic table sizing */
  304. count_int fsize;
  305.  
  306. /*
  307.  * To save much memory, we overlay the table used by compress() with those
  308.  * used by decompress().  The tab_prefix table is the same size and type
  309.  * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  310.  * get this from the beginning of htab.  The output stack uses the rest
  311.  * of htab, and contains characters.  There is plenty of room for any
  312.  * possible stack (stack used to be 8000 characters).
  313.  */
  314.  
  315. #define tab_prefixof(i) codetabof(i)
  316. #ifdef XENIX_16
  317. # define tab_suffixof(i)        ((char_type *)htab[(i)>>15])[(i) & 0x7fff]
  318. # define de_stack               ((char_type *)(htab2))
  319. #else   /* Normal machine */
  320. # define tab_suffixof(i)        ((char_type *)(htab))[i]
  321. # define de_stack               ((char_type *)&tab_suffixof(1<<BITS))
  322. #endif  /* XENIX_16 */
  323.  
  324. code_int free_ent = 0;                  /* first unused entry */
  325. int exit_stat = 0;
  326.  
  327. code_int getcode();
  328.  
  329. Usage() {
  330. #ifdef DEBUG
  331. fprintf(stderr,"Usage: compress [-dDVfc] [-b maxbits] [file ...]\n");
  332. }
  333. int debug = 0;
  334. #else
  335. fprintf(stderr,"Usage: compress [-dfvcV] [-b maxbits] [file ...]\n");
  336. }
  337. #endif /* DEBUG */
  338. int nomagic = 0;        /* Use a 3-byte magic number header, unless old file */
  339. int zcat_flg = 0;       /* Write output on stdout, suppress messages */
  340. int quiet = 1;          /* don't tell me about compression */
  341.  
  342. /*
  343.  * block compression parameters -- after all codes are used up,
  344.  * and compression rate changes, start over.
  345.  */
  346. int block_compress = BLOCK_MASK;
  347. int clear_flg = 0;
  348. long int ratio = 0;
  349. #define CHECK_GAP 10000 /* ratio check interval */
  350. count_int checkpoint = CHECK_GAP;
  351. /*
  352.  * the next two codes should not be changed lightly, as they must not
  353.  * lie within the contiguous general code space.
  354.  */ 
  355. #define FIRST   257     /* first free entry */
  356. #define CLEAR   256     /* table clear output code */
  357.  
  358. int force = 0;
  359. char ofname [100];
  360. #ifdef DEBUG
  361. int verbose = 0;
  362. #endif /* DEBUG */
  363. int (*bgnd_flag)();
  364.  
  365. int do_decomp = 0;
  366.  
  367. /*****************************************************************
  368.  * TAG( main )
  369.  *
  370.  * Algorithm from "A Technique for High Performance Data Compression",
  371.  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
  372.  *
  373.  * Usage: compress [-dfvc] [-b bits] [file ...]
  374.  * Inputs:
  375.  *      -d:         If given, decompression is done instead.
  376.  *
  377.  *      -c:         Write output on stdout, don't remove original.
  378.  *
  379.  *      -b:         Parameter limits the max number of bits/code.
  380.  *
  381.  *      -f:         Forces output file to be generated, even if one already
  382.  *                  exists, and even if no space is saved by compressing.
  383.  *                  If -f is not used, the user will be prompted if stdin is
  384.  *                  a tty, otherwise, the output file will not be overwritten.
  385.  *
  386.  *      -v:         Write compression statistics
  387.  *
  388.  *      file ...:   Files to be compressed.  If none specified, stdin
  389.  *                  is used.
  390.  * Outputs:
  391.  *      file.Z:     Compressed form of file with same mode, owner, and utimes
  392.  *      or stdout   (if stdin used as input)
  393.  *
  394.  * Assumptions:
  395.  *      When filenames are given, replaces with the compressed version
  396.  *      (.Z suffix) only if the file decreases in size.
  397.  * Algorithm:
  398.  *      Modified Lempel-Ziv method (LZW).  Basically finds common
  399.  * substrings and replaces them with a variable size code.  This is
  400.  * deterministic, and can be done on the fly.  Thus, the decompression
  401.  * procedure needs no input table, but tracks the way the table was built.
  402.  */
  403.  
  404. _main( argc, argv )
  405. register int argc; char **argv;
  406. {
  407.     int overwrite = 0;  /* Do not overwrite unless given -f flag */
  408.     char tempname[100];
  409.     char **filelist, **fileptr;
  410.     char *cp, *rindex(), *malloc();
  411.  
  412.  
  413. #ifdef COMPATIBLE
  414.     nomagic = 1;        /* Original didn't have a magic number */
  415. #endif /* COMPATIBLE */
  416.  
  417.     htab=(count_int *)malloc(sizeof(count_int)*HSIZE);
  418.     codetab=(unsigned short *)malloc(sizeof(unsigned short)*HSIZE);
  419.     if ((htab==NULL) || (codetab==NULL)) SysBeep(120);
  420.     filelist = fileptr = (char **)(malloc(argc * sizeof(*argv)));
  421.     *filelist = NULL;
  422.  
  423.     if((cp = rindex(argv[0], '/')) != 0) {
  424.         cp++;
  425.     } else {
  426.         cp = argv[0];
  427.     }
  428.     if(strcmp(cp, "uncompress") == 0) {
  429.         do_decomp = 1;
  430.     } else if(strcmp(cp, "zcat") == 0) {
  431.         do_decomp = 1;
  432.         zcat_flg = 1;
  433.     }
  434.  
  435. #ifdef BSD4_2
  436.     /* 4.2BSD dependent - take it out if not */
  437.     setlinebuf( stderr );
  438. #endif /* BSD4_2 */
  439.  
  440.     /* Argument Processing
  441.      * All flags are optional.
  442.      * -D => debug
  443.      * -V => print Version; debug verbose
  444.      * -d => do_decomp
  445.      * -v => unquiet
  446.      * -f => force overwrite of output file
  447.      * -n => no header: useful to uncompress old files
  448.      * -b maxbits => maxbits.  If -b is specified, then maxbits MUST be
  449.      *      given also.
  450.      * -c => cat all output to stdout
  451.      * -C => generate output compatible with compress 2.0.
  452.      * if a string is left, must be an input filename.
  453.      */
  454.     for (argc--, argv++; argc > 0; argc--, argv++) {
  455.         if (**argv == '-') {    /* A flag argument */
  456.             while (*++(*argv)) {        /* Process all flags in this arg */
  457.                 switch (**argv) {
  458. #ifdef DEBUG
  459.                     case 'D':
  460.                         debug = 1;
  461.                         break;
  462.                     case 'V':
  463.                         verbose = 1;
  464.                         version();
  465.                         break;
  466. #else
  467.                     case 'V':
  468.                         version();
  469.                         break;
  470. #endif /* DEBUG */
  471.                     case 'v':
  472.                         quiet = 0;
  473.                         break;
  474.                     case 'd':
  475.                         do_decomp = 1;
  476.                         break;
  477.                     case 'f':
  478.                     case 'F':
  479.                         overwrite = 1;
  480.                         force = 1;
  481.                         break;
  482.                     case 'n':
  483.                         nomagic = 1;
  484.                         break;
  485.                     case 'C':
  486.                         block_compress = 0;
  487.                         break;
  488.                     case 'b':
  489.                         if (!ARGVAL()) {
  490.                             fprintf(stderr, "Missing maxbits\n");
  491.                             Usage();
  492.                             exit(1);
  493.                         }
  494.                         maxbits = atoi(*argv);
  495.                         goto nextarg;
  496.                     case 'c':
  497.                         zcat_flg = 1;
  498.                         break;
  499.                     case 'q':
  500.                         quiet = 1;
  501.                         break;
  502.                     default:
  503.                         fprintf(stderr, "Unknown flag: '%c'; ", **argv);
  504.                         Usage();
  505.                         exit(1);
  506.                 }
  507.             }
  508.         }
  509.         else {          /* Input file name */
  510.             *fileptr++ = *argv; /* Build input file list */
  511.             *fileptr = NULL;
  512.             /* process nextarg; */
  513.         }
  514.         nextarg: continue;
  515.     }
  516.  
  517.     if(maxbits < INIT_BITS) maxbits = INIT_BITS;
  518.     if (maxbits > BITS) maxbits = BITS;
  519.     maxmaxcode = 1 << maxbits;
  520.  
  521.     if (*filelist != NULL) {
  522.         for (fileptr = filelist; *fileptr; fileptr++) {
  523.             exit_stat = 0;
  524.             if (do_decomp != 0) {                       /* DECOMPRESSION */
  525.                 /* Check for .Z suffix */
  526.                 if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") != 0) {
  527.                     /* No .Z: tack one on */
  528.                     strcpy(tempname, *fileptr);
  529.                     strcat(tempname, ".Z");
  530.                     *fileptr = tempname;
  531.                 }
  532.                 /* Open input file */
  533.                 if ((freopen(*fileptr, "r", stdin)) == NULL) {
  534.                         perror(*fileptr); continue;
  535.                 }
  536.                 /* Check the magic number */
  537.                 if (nomagic == 0) {
  538.                     if ((getchar() != (magic_header[0] & 0xFF))
  539.                      || (getchar() != (magic_header[1] & 0xFF))) {
  540.                         fprintf(stderr, "%s: not in compressed format\n",
  541.                             *fileptr);
  542.                     continue;
  543.                     }
  544.                     maxbits = getchar();        /* set -b from file */
  545.                     block_compress = maxbits & BLOCK_MASK;
  546.                     maxbits &= BIT_MASK;
  547.                     maxmaxcode = 1 << maxbits;
  548.                     if(maxbits > BITS) {
  549.                         fprintf(stderr,
  550.                         "%s: compressed with %d bits, can only handle %d bits\n",
  551.                         *fileptr, maxbits, BITS);
  552.                         continue;
  553.                     }
  554.                 }
  555.                 /* Generate output filename */
  556.                 strcpy(ofname, *fileptr);
  557.                 ofname[strlen(*fileptr) - 2] = '\0';  /* Strip off .Z */
  558.             } else {                                    /* COMPRESSION */
  559.                 if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") == 0) {
  560.                         fprintf(stderr, "%s: already has .Z suffix -- no change\n",
  561.                             *fileptr);
  562.                     continue;
  563.                 }
  564.                 /* Open input file */
  565.                 if ((freopen(*fileptr, "r", stdin)) == NULL) {
  566.                     perror(*fileptr); continue;
  567.                 }
  568.  
  569.                 /* Generate output filename */
  570.                 strcpy(ofname, *fileptr);
  571. #ifndef BSD4_2          /* Short filenames */
  572.                 if ((cp=rindex(ofname,'/')) != NULL)    cp++;
  573.                 else                                    cp = ofname;
  574.                 if (strlen(cp) > 12) {
  575.                     fprintf(stderr,"%s: filename too long to tack on .Z\n",cp);
  576.                     continue;
  577.                 }
  578. #endif  /* BSD4_2               Long filenames allowed */
  579.                 strcat(ofname, ".Z");
  580.             }
  581.             if(zcat_flg == 0) {         /* Open output file */
  582.                 if (freopen(ofname, "w", stdout) == NULL) {
  583.                     perror(ofname);
  584.                     continue;
  585.                 }
  586.                 if(!quiet)
  587.                         fprintf(stderr, "%s: ", *fileptr);
  588.             }
  589.  
  590.             /* Actually do the compression/decompression */
  591.             if (do_decomp == 0) compress();
  592. #ifndef DEBUG
  593.             else                        decompress();
  594. #else
  595.             else if (debug == 0)        decompress();
  596.             else                        printcodes();
  597.             if (verbose)                dump_tab();
  598. #endif /* DEBUG */
  599.             if(zcat_flg == 0) {
  600.                 copystat(*fileptr, ofname);     /* Copy stats */
  601.                 if((exit_stat == 1) || (!quiet))
  602.                         putc('\n', stderr);
  603.             }
  604.         }
  605.     } else {            /* Standard input */
  606.         if (do_decomp == 0) {
  607.                 compress();
  608. #ifdef DEBUG
  609.                 if(verbose)             dump_tab();
  610. #endif /* DEBUG */
  611.                 if(!quiet)
  612.                         putc('\n', stderr);
  613.         } else {
  614.             /* Check the magic number */
  615.             if (nomagic == 0) {
  616.                 if ((getchar()!=(magic_header[0] & 0xFF))
  617.                  || (getchar()!=(magic_header[1] & 0xFF))) {
  618.                     fprintf(stderr, "stdin: not in compressed format\n");
  619.                     exit(1);
  620.                 }
  621.                 maxbits = getchar();    /* set -b from file */
  622.                 block_compress = maxbits & BLOCK_MASK;
  623.                 maxbits &= BIT_MASK;
  624.                 maxmaxcode = 1 << maxbits;
  625.                 fsize = 100000;         /* assume stdin large for USERMEM */
  626.                 if(maxbits > BITS) {
  627.                         fprintf(stderr,
  628.                         "stdin: compressed with %d bits, can only handle %d bits\n",
  629.                         maxbits, BITS);
  630.                         exit(1);
  631.                 }
  632.             }
  633. #ifndef DEBUG
  634.             decompress();
  635. #else
  636.             if (debug == 0)     decompress();
  637.             else                printcodes();
  638.             if (verbose)        dump_tab();
  639. #endif /* DEBUG */
  640.         }
  641.     }
  642.     exit(exit_stat);
  643. }
  644.  
  645. static int offset;
  646. long int in_count = 1;                  /* length of input */
  647. long int bytes_out;                     /* length of compressed output */
  648. long int out_count = 0;                 /* # of codes output (for debugging) */
  649.  
  650. /*
  651.  * compress stdin to stdout
  652.  *
  653.  * Algorithm:  use open addressing double hashing (no chaining) on the 
  654.  * prefix code / next character combination.  We do a variant of Knuth's
  655.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  656.  * secondary probe.  Here, the modular division first probe is gives way
  657.  * to a faster exclusive-or manipulation.  Also do block compression with
  658.  * an adaptive reset, whereby the code table is cleared when the compression
  659.  * ratio decreases, but after the table fills.  The variable-length output
  660.  * codes are re-sized at this point, and a special CLEAR code is generated
  661.  * for the decompressor.  Late addition:  construct the table according to
  662.  * file size for noticeable speed improvement on small files.  Please direct
  663.  * questions about this implementation to ames!jaw.
  664.  */
  665.  
  666. compress() {
  667.     register long fcode;
  668.     register code_int i = 0;
  669.     register int c;
  670.     register code_int ent;
  671. #ifdef XENIX_16
  672.     register code_int disp;
  673. #else   /* Normal machine */
  674.     register int disp;
  675. #endif
  676.     register code_int hsize_reg;
  677.     register int hshift;
  678.  
  679. #ifndef COMPATIBLE
  680.     if (nomagic == 0) {
  681.         putchar(magic_header[0]); putchar(magic_header[1]);
  682.         putchar((char)(maxbits | block_compress));
  683.         if(ferror(stdout))
  684.                 writeerr();
  685.     }
  686. #endif /* COMPATIBLE */
  687.  
  688.     offset = 0;
  689.     bytes_out = 3;              /* includes 3-byte header mojo */
  690.     out_count = 0;
  691.     clear_flg = 0;
  692.     ratio = 0;
  693.     in_count = 1;
  694.     checkpoint = CHECK_GAP;
  695.     maxcode = MAXCODE(n_bits = INIT_BITS);
  696.     free_ent = ((block_compress) ? FIRST : 256 );
  697.  
  698.     ent = getchar ();
  699.  
  700.     hshift = 0;
  701.     for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  702.         hshift++;
  703.     hshift = 8 - hshift;                /* set hash code range bound */
  704.  
  705.     hsize_reg = hsize;
  706.     cl_hash( (count_int) hsize_reg);            /* clear hash table */
  707.  
  708. #ifdef SIGNED_COMPARE_SLOW
  709.     while ( (c = getchar()) != (unsigned) EOF ) {
  710. #else
  711.     while ( (c = getchar()) != EOF ) {
  712. #endif
  713.         in_count++;
  714.         fcode = (long) (((long) c << maxbits) + ent);
  715.         i = ((c << hshift) ^ ent);      /* xor hashing */
  716.  
  717.         if ( htabof (i) == fcode ) {
  718.             ent = codetabof (i);
  719.             continue;
  720.         } else if ( (long)htabof (i) < 0 )      /* empty slot */
  721.             goto nomatch;
  722.         disp = hsize_reg - i;           /* secondary hash (after G. Knott) */
  723.         if ( i == 0 )
  724.             disp = 1;
  725. probe:
  726.         if ( (i -= disp) < 0 )
  727.             i += hsize_reg;
  728.  
  729.         if ( htabof (i) == fcode ) {
  730.             ent = codetabof (i);
  731.             continue;
  732.         }
  733.         if ( (long)htabof (i) > 0 ) 
  734.             goto probe;
  735. nomatch:
  736.         output ( (code_int) ent );
  737.         out_count++;
  738.         ent = c;
  739. #ifdef SIGNED_COMPARE_SLOW
  740.         if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  741. #else
  742.         if ( free_ent < maxmaxcode ) {
  743. #endif
  744.             codetabof (i) = free_ent++; /* code -> hashtable */
  745.             htabof (i) = fcode;
  746.         }
  747.         else if ( (count_int)in_count >= checkpoint && block_compress )
  748.             cl_block ();
  749.     }
  750.     /*
  751.      * Put out the final code.
  752.      */
  753.     output( (code_int)ent );
  754.     out_count++;
  755.     output( (code_int)-1 );
  756.  
  757.     /*
  758.      * Print out stats on stderr
  759.      */
  760.     if(zcat_flg == 0 && !quiet) {
  761. #ifdef DEBUG
  762.         fprintf( stderr,
  763.                 "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
  764.                 in_count, out_count, bytes_out );
  765.         prratio( stderr, in_count, bytes_out );
  766.         fprintf( stderr, "\n");
  767.         fprintf( stderr, "\tCompression as in compact: " );
  768.         prratio( stderr, in_count-bytes_out, in_count );
  769.         fprintf( stderr, "\n");
  770.         fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
  771.                 free_ent - 1, n_bits );
  772. #else /* !DEBUG */
  773.         fprintf( stderr, "Compression: " );
  774.         prratio( stderr, in_count-bytes_out, in_count );
  775. #endif /* DEBUG */
  776.     }
  777.     if(bytes_out > in_count)    /* exit(2) if no savings */
  778.         exit_stat = 2;
  779.     return;
  780. }
  781.  
  782. /*****************************************************************
  783.  * TAG( output )
  784.  *
  785.  * Output the given code.
  786.  * Inputs:
  787.  *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
  788.  *              that n_bits =< (long)wordsize - 1.
  789.  * Outputs:
  790.  *      Outputs code to the file.
  791.  * Assumptions:
  792.  *      Chars are 8 bits long.
  793.  * Algorithm:
  794.  *      Maintain a BITS character long buffer (so that 8 codes will
  795.  * fit in it exactly).  Use the VAX insv instruction to insert each
  796.  * code in turn.  When the buffer fills up empty it and start over.
  797.  */
  798.  
  799. static char buf[BITS];
  800.  
  801. #ifndef vax
  802. char_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
  803. char_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
  804. #endif /* vax */
  805.  
  806. output( code )
  807. code_int  code;
  808. {
  809. #ifdef DEBUG
  810.     static int col = 0;
  811. #endif /* DEBUG */
  812.  
  813.     /*
  814.      * On the VAX, it is important to have the register declarations
  815.      * in exactly the order given, or the asm will break.
  816.      */
  817.     register int r_off = offset, bits= n_bits;
  818.     register char * bp = buf;
  819.  
  820. #ifdef DEBUG
  821.         if ( verbose )
  822.             fprintf( stderr, "%5d%c", code,
  823.                     (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  824. #endif /* DEBUG */
  825.     if ( code >= 0 ) {
  826. #ifdef vax
  827.         /* VAX DEPENDENT!! Implementation on other machines is below.
  828.          *
  829.          * Translation: Insert BITS bits from the argument starting at
  830.          * offset bits from the beginning of buf.
  831.          */
  832.         0;      /* Work around for pcc -O bug with asm and if stmt */
  833.         asm( "insv      4(ap),r11,r10,(r9)" );
  834. #else /* not a vax */
  835. /* 
  836.  * byte/bit numbering on the VAX is simulated by the following code
  837.  */
  838.         /*
  839.          * Get to the first byte.
  840.          */
  841.         bp += (r_off >> 3);
  842.         r_off &= 7;
  843.         /*
  844.          * Since code is always >= 8 bits, only need to mask the first
  845.          * hunk on the left.
  846.          */
  847.         *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
  848.         bp++;
  849.         bits -= (8 - r_off);
  850.         code >>= 8 - r_off;
  851.         /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  852.         if ( bits >= 8 ) {
  853.             *bp++ = code;
  854.             code >>= 8;
  855.             bits -= 8;
  856.         }
  857.         /* Last bits. */
  858.         if(bits)
  859.             *bp = code;
  860. #endif /* vax */
  861.         offset += n_bits;
  862.         if ( offset == (n_bits << 3) ) {
  863.             bp = buf;
  864.             bits = n_bits;
  865.             bytes_out += bits;
  866.             do
  867.                 putchar(*bp++);
  868.             while(--bits);
  869.             offset = 0;
  870.         }
  871.  
  872.         /*
  873.          * If the next entry is going to be too big for the code size,
  874.          * then increase it, if possible.
  875.          */
  876.         if ( free_ent > maxcode || (clear_flg > 0))
  877.         {
  878.             /*
  879.              * Write the whole buffer, because the input side won't
  880.              * discover the size increase until after it has read it.
  881.              */
  882.             if ( offset > 0 ) {
  883.                 if( fwrite( buf, 1, n_bits, stdout ) != n_bits)
  884.                         writeerr();
  885.                 bytes_out += n_bits;
  886.             }
  887.             offset = 0;
  888.  
  889.             if ( clear_flg ) {
  890.                 maxcode = MAXCODE (n_bits = INIT_BITS);
  891.                 clear_flg = 0;
  892.             }
  893.             else {
  894.                 n_bits++;
  895.                 if ( n_bits == maxbits )
  896.                     maxcode = maxmaxcode;
  897.                 else
  898.                     maxcode = MAXCODE(n_bits);
  899.             }
  900. #ifdef DEBUG
  901.             if ( debug ) {
  902.                 fprintf( stderr, "\nChange to %d bits\n", n_bits );
  903.                 col = 0;
  904.             }
  905. #endif /* DEBUG */
  906.         }
  907.     } else {
  908.         /*
  909.          * At EOF, write the rest of the buffer.
  910.          */
  911.         if ( offset > 0 )
  912.             fwrite( buf, 1, (offset + 7) / 8, stdout );
  913.         bytes_out += (offset + 7) / 8;
  914.         offset = 0;
  915.         fflush( stdout );
  916. #ifdef DEBUG
  917.         if ( verbose )
  918.             fprintf( stderr, "\n" );
  919. #endif /* DEBUG */
  920.         if( ferror( stdout ) )
  921.                 writeerr();
  922.     }
  923. }
  924.  
  925. /*
  926.  * Decompress stdin to stdout.  This routine adapts to the codes in the
  927.  * file building the "string" table on-the-fly; requiring no table to
  928.  * be stored in the compressed file.  The tables used herein are shared
  929.  * with those of the compress() routine.  See the definitions above.
  930.  */
  931.  
  932. decompress() {
  933.     register char_type *stackp;
  934.     register int finchar;
  935.     register code_int code, oldcode, incode;
  936.  
  937.     /*
  938.      * As above, initialize the first 256 entries in the table.
  939.      */
  940.     maxcode = MAXCODE(n_bits = INIT_BITS);
  941.     for ( code = 255; code >= 0; code-- ) {
  942.         tab_prefixof(code) = 0;
  943.         tab_suffixof(code) = (char_type)code;
  944.     }
  945.     free_ent = ((block_compress) ? FIRST : 256 );
  946.  
  947.     finchar = oldcode = getcode();
  948.     if(oldcode == -1)   /* EOF already? */
  949.         return;                 /* Get out of here */
  950.     putchar( (char)finchar );           /* first code must be 8 bits = char */
  951.     if(ferror(stdout))          /* Crash if can't write */
  952.         writeerr();
  953.     stackp = de_stack;
  954.  
  955.     while ( (code = getcode()) > -1 ) {
  956.  
  957.         if ( (code == CLEAR) && block_compress ) {
  958.             for ( code = 255; code >= 0; code-- )
  959.                 tab_prefixof(code) = 0;
  960.             clear_flg = 1;
  961.             free_ent = FIRST - 1;
  962.             if ( (code = getcode ()) == -1 )    /* O, untimely death! */
  963.                 break;
  964.         }
  965.         incode = code;
  966.         /*
  967.          * Special case for KwKwK string.
  968.          */
  969.         if ( code >= free_ent ) {
  970.             *stackp++ = finchar;
  971.             code = oldcode;
  972.         }
  973.  
  974.         /*
  975.          * Generate output characters in reverse order
  976.          */
  977. #ifdef SIGNED_COMPARE_SLOW
  978.         while ( ((unsigned long)code) >= ((unsigned long)256) ) {
  979. #else
  980.         while ( code >= 256 ) {
  981. #endif
  982.             *stackp++ = tab_suffixof(code);
  983.             code = tab_prefixof(code);
  984.         }
  985.         *stackp++ = finchar = tab_suffixof(code);
  986.  
  987.         /*
  988.          * And put them out in forward order
  989.          */
  990.         do
  991.             putchar ( *--stackp );
  992.         while ( stackp > de_stack );
  993.  
  994.         /*
  995.          * Generate the new entry.
  996.          */
  997.         if ( (code=free_ent) < maxmaxcode ) {
  998.             tab_prefixof(code) = (unsigned short)oldcode;
  999.             tab_suffixof(code) = finchar;
  1000.             free_ent = code+1;
  1001.         } 
  1002.         /*
  1003.          * Remember previous code.
  1004.          */
  1005.         oldcode = incode;
  1006.     }
  1007.     fflush( stdout );
  1008.     if(ferror(stdout))
  1009.         writeerr();
  1010. }
  1011.  
  1012. /*****************************************************************
  1013.  * TAG( getcode )
  1014.  *
  1015.  * Read one code from the standard input.  If EOF, return -1.
  1016.  * Inputs:
  1017.  *      stdin
  1018.  * Outputs:
  1019.  *      code or -1 is returned.
  1020.  */
  1021.  
  1022. code_int
  1023. getcode() {
  1024.     /*
  1025.      * On the VAX, it is important to have the register declarations
  1026.      * in exactly the order given, or the asm will break.
  1027.      */
  1028.     register code_int code;
  1029.     static int offset = 0, size = 0;
  1030.     static char_type buf[BITS];
  1031.     register int r_off, bits;
  1032.     register char_type *bp = buf;
  1033.  
  1034.     if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
  1035.         /*
  1036.          * If the next entry will be too big for the current code
  1037.          * size, then we must increase the size.  This implies reading
  1038.          * a new buffer full, too.
  1039.          */
  1040.         if ( free_ent > maxcode ) {
  1041.             n_bits++;
  1042.             if ( n_bits == maxbits )
  1043.                 maxcode = maxmaxcode;   /* won't get any bigger now */
  1044.             else
  1045.                 maxcode = MAXCODE(n_bits);
  1046.         }
  1047.         if ( clear_flg > 0) {
  1048.             maxcode = MAXCODE (n_bits = INIT_BITS);
  1049.             clear_flg = 0;
  1050.         }
  1051.         size = fread( buf, 1, n_bits, stdin );
  1052.         if ( size <= 0 )
  1053.             return -1;                  /* end of file */
  1054.         offset = 0;
  1055.         /* Round size down to integral number of codes */
  1056.         size = (size << 3) - (n_bits - 1);
  1057.     }
  1058.     r_off = offset;
  1059.     bits = n_bits;
  1060. #ifdef vax
  1061.     asm( "extzv   r10,r9,(r8),r11" );
  1062. #else /* not a vax */
  1063.         /*
  1064.          * Get to the first byte.
  1065.          */
  1066.         bp += (r_off >> 3);
  1067.         r_off &= 7;
  1068.         /* Get first part (low order bits) */
  1069. #ifdef NO_UCHAR
  1070.         code = ((*bp++ >> r_off) & rmask[8 - r_off]) & 0xff;
  1071. #else
  1072.         code = (*bp++ >> r_off);
  1073. #endif /* NO_UCHAR */
  1074.         bits -= (8 - r_off);
  1075.         r_off = 8 - r_off;              /* now, offset into code word */
  1076.         /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  1077.         if ( bits >= 8 ) {
  1078. #ifdef NO_UCHAR
  1079.             code |= (*bp++ & 0xff) << r_off;
  1080. #else
  1081.             code |= *bp++ << r_off;
  1082. #endif /* NO_UCHAR */
  1083.             r_off += 8;
  1084.             bits -= 8;
  1085.         }
  1086.         /* high order bits. */
  1087.         code |= (*bp & rmask[bits]) << r_off;
  1088. #endif /* vax */
  1089.     offset += n_bits;
  1090.  
  1091.     return code;
  1092. }
  1093.  
  1094. char *
  1095. rindex(s, c)            /* For those who don't have it in libc.a */
  1096. register char *s, c;
  1097. {
  1098.         char *p;
  1099.         for (p = NULL; *s; s++)
  1100.             if (*s == c)
  1101.                 p = s;
  1102.         return(p);
  1103. }
  1104.  
  1105. #ifdef DEBUG
  1106. printcodes()
  1107. {
  1108.     /*
  1109.      * Just print out codes from input file.  For debugging.
  1110.      */
  1111.     code_int code;
  1112.     int col = 0, bits;
  1113.  
  1114.     bits = n_bits = INIT_BITS;
  1115.     maxcode = MAXCODE(n_bits);
  1116.     free_ent = ((block_compress) ? FIRST : 256 );
  1117.     while ( ( code = getcode() ) >= 0 ) {
  1118.         if ( (code == CLEAR) && block_compress ) {
  1119.             free_ent = FIRST - 1;
  1120.             clear_flg = 1;
  1121.         }
  1122.         else if ( free_ent < maxmaxcode )
  1123.             free_ent++;
  1124.         if ( bits != n_bits ) {
  1125.             fprintf(stderr, "\nChange to %d bits\n", n_bits );
  1126.             bits = n_bits;
  1127.             col = 0;
  1128.         }
  1129.         fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  1130.     }
  1131.     putc( '\n', stderr );
  1132.     exit( 0 );
  1133. }
  1134.  
  1135. code_int sorttab[1<<BITS];      /* sorted pointers into htab */
  1136.  
  1137. dump_tab()      /* dump string table */
  1138. {
  1139.     register int i, first;
  1140.     register ent;
  1141. #define STACK_SIZE      15000
  1142.     int stack_top = STACK_SIZE;
  1143.     register c;
  1144.  
  1145.     if(do_decomp == 0) {        /* compressing */
  1146.         register int flag = 1;
  1147.  
  1148.         for(i=0; i<hsize; i++) {        /* build sort pointers */
  1149.                 if((long)htabof(i) >= 0) {
  1150.                         sorttab[codetabof(i)] = i;
  1151.                 }
  1152.         }
  1153.         first = block_compress ? FIRST : 256;
  1154.         for(i = first; i < free_ent; i++) {
  1155.                 fprintf(stderr, "%5d: \"", i);
  1156.                 de_stack[--stack_top] = '\n';
  1157.                 de_stack[--stack_top] = '"';
  1158.                 stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff, 
  1159.                                      stack_top);
  1160.                 for(ent=htabof(sorttab[i]) & ((1<<maxbits)-1);
  1161.                     ent > 256;
  1162.                     ent=htabof(sorttab[ent]) & ((1<<maxbits)-1)) {
  1163.                         stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
  1164.                                                 stack_top);
  1165.                 }
  1166.                 stack_top = in_stack(ent, stack_top);
  1167.                 fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
  1168.                 stack_top = STACK_SIZE;
  1169.         }
  1170.    } else if(!debug) {  /* decompressing */
  1171.  
  1172.        for ( i = 0; i < free_ent; i++ ) {
  1173.            ent = i;
  1174.            c = tab_suffixof(ent);
  1175.            if ( isascii(c) && isprint(c) )
  1176.                fprintf( stderr, "%5d: %5d/'%c'  \"",
  1177.                            ent, tab_prefixof(ent), c );
  1178.            else
  1179.                fprintf( stderr, "%5d: %5d/\\%03o \"",
  1180.                            ent, tab_prefixof(ent), c );
  1181.            de_stack[--stack_top] = '\n';
  1182.            de_stack[--stack_top] = '"';
  1183.            for ( ; ent != NULL;
  1184.                    ent = (ent >= FIRST ? tab_prefixof(ent) : NULL) ) {
  1185.                stack_top = in_stack(tab_suffixof(ent), stack_top);
  1186.            }
  1187.            fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
  1188.            stack_top = STACK_SIZE;
  1189.        }
  1190.     }
  1191. }
  1192.  
  1193. int
  1194. in_stack(c, stack_top)
  1195.         register c, stack_top;
  1196. {
  1197.         if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
  1198.             de_stack[--stack_top] = c;
  1199.         } else {
  1200.             switch( c ) {
  1201.             case '\n': de_stack[--stack_top] = 'n'; break;
  1202.             case '\t': de_stack[--stack_top] = 't'; break;
  1203.             case '\b': de_stack[--stack_top] = 'b'; break;
  1204.             case '\f': de_stack[--stack_top] = 'f'; break;
  1205.             case '\r': de_stack[--stack_top] = 'r'; break;
  1206.             case '\\': de_stack[--stack_top] = '\\'; break;
  1207.             default:
  1208.                 de_stack[--stack_top] = '0' + c % 8;
  1209.                 de_stack[--stack_top] = '0' + (c / 8) % 8;
  1210.                 de_stack[--stack_top] = '0' + c / 64;
  1211.                 break;
  1212.             }
  1213.             de_stack[--stack_top] = '\\';
  1214.         }
  1215.         return stack_top;
  1216. }
  1217. #endif /* DEBUG */
  1218.  
  1219. writeerr()
  1220. {
  1221.     perror ( ofname );
  1222.     unlink ( ofname );
  1223.     exit ( 1 );
  1224. }
  1225.  
  1226. copystat(ifname, ofname)
  1227. char *ifname, *ofname;
  1228. {
  1229.     int mode;
  1230.  
  1231.     fclose(stdout);
  1232.     exit_stat = 0;
  1233.     return;         /* Successful return */
  1234. }
  1235.  
  1236. /*
  1237.  * This routine returns 1 if we are running in the foreground and stderr
  1238.  * is a tty.
  1239.  */
  1240. foreground()
  1241. {
  1242.     return(1);
  1243. }
  1244.  
  1245. onintr ( )
  1246. {
  1247.     unlink ( ofname );
  1248.     exit ( 1 );
  1249. }
  1250.  
  1251. oops ( )        /* wild pointer -- assume bad input */
  1252. {
  1253.     if ( do_decomp == 1 ) 
  1254.         fprintf ( stderr, "uncompress: corrupt input\n" );
  1255.     unlink ( ofname );
  1256.     exit ( 1 );
  1257. }
  1258.  
  1259. cl_block ()             /* table clear for block compress */
  1260. {
  1261.     register long int rat;
  1262.  
  1263.     checkpoint = in_count + CHECK_GAP;
  1264. #ifdef DEBUG
  1265.         if ( debug ) {
  1266.                 fprintf ( stderr, "count: %ld, ratio: ", in_count );
  1267.                 prratio ( stderr, in_count, bytes_out );
  1268.                 fprintf ( stderr, "\n");
  1269.         }
  1270. #endif /* DEBUG */
  1271.  
  1272.     if(in_count > 0x007fffff) { /* shift will overflow */
  1273.         rat = bytes_out >> 8;
  1274.         if(rat == 0) {          /* Don't divide by zero */
  1275.             rat = 0x7fffffff;
  1276.         } else {
  1277.             rat = in_count / rat;
  1278.         }
  1279.     } else {
  1280.         rat = (in_count << 8) / bytes_out;      /* 8 fractional bits */
  1281.     }
  1282.     if ( rat > ratio ) {
  1283.         ratio = rat;
  1284.     } else {
  1285.         ratio = 0;
  1286. #ifdef DEBUG
  1287.         if(verbose)
  1288.                 dump_tab();     /* dump string table */
  1289. #endif
  1290.         cl_hash ( (count_int) hsize );
  1291.         free_ent = FIRST;
  1292.         clear_flg = 1;
  1293.         output ( (code_int) CLEAR );
  1294. #ifdef DEBUG
  1295.         if(debug)
  1296.                 fprintf ( stderr, "clear\n" );
  1297. #endif /* DEBUG */
  1298.     }
  1299. }
  1300.  
  1301. cl_hash(hsize)          /* reset code table */
  1302.         register count_int hsize;
  1303. {
  1304. #ifndef XENIX_16        /* Normal machine */
  1305.         register count_int *htab_p = htab+hsize;
  1306. #else
  1307.         register j;
  1308.         register long k = hsize;
  1309.         register count_int *htab_p;
  1310. #endif
  1311.         register long i;
  1312.         register long m1 = -1;
  1313.  
  1314. #ifdef XENIX_16
  1315.     for(j=0; j<=8 && k>=0; j++,k-=8192) {
  1316.         i = 8192;
  1317.         if(k < 8192) {
  1318.                 i = k;
  1319.         }
  1320.         htab_p = &(htab[j][i]);
  1321.         i -= 16;
  1322.         if(i > 0) {
  1323. #else
  1324.         i = hsize - 16;
  1325. #endif
  1326.         do {                            /* might use Sys V memset(3) here */
  1327.                 *(htab_p-16) = m1;
  1328.                 *(htab_p-15) = m1;
  1329.                 *(htab_p-14) = m1;
  1330.                 *(htab_p-13) = m1;
  1331.                 *(htab_p-12) = m1;
  1332.                 *(htab_p-11) = m1;
  1333.                 *(htab_p-10) = m1;
  1334.                 *(htab_p-9) = m1;
  1335.                 *(htab_p-8) = m1;
  1336.                 *(htab_p-7) = m1;
  1337.                 *(htab_p-6) = m1;
  1338.                 *(htab_p-5) = m1;
  1339.                 *(htab_p-4) = m1;
  1340.                 *(htab_p-3) = m1;
  1341.                 *(htab_p-2) = m1;
  1342.                 *(htab_p-1) = m1;
  1343.                 htab_p -= 16;
  1344.         } while ((i -= 16) >= 0);
  1345. #ifdef XENIX_16
  1346.         }
  1347.     }
  1348. #endif
  1349.         for ( i += 16; i > 0; i-- )
  1350.                 *--htab_p = m1;
  1351. }
  1352.  
  1353. prratio(stream, num, den)
  1354. FILE *stream;
  1355. long int num, den;
  1356. {
  1357.         register int q;                 /* Doesn't need to be long */
  1358.  
  1359.         if(num > 214748L) {             /* 2147483647/10000 */
  1360.                 q = num / (den / 10000L);
  1361.         } else {
  1362.                 q = 10000L * num / den;         /* Long calculations, though */
  1363.         }
  1364.         if (q < 0) {
  1365.                 putc('-', stream);
  1366.                 q = -q;
  1367.         }
  1368.         fprintf(stream, "%d.%02d%%", q / 100, q % 100);
  1369. }
  1370.  
  1371. version()
  1372. {
  1373.         fprintf(stderr, "%s\n", rcs_ident);
  1374.         fprintf(stderr, "Options: ");
  1375. #ifdef vax
  1376.         fprintf(stderr, "vax, ");
  1377. #endif
  1378. #ifdef NO_UCHAR
  1379.         fprintf(stderr, "NO_UCHAR, ");
  1380. #endif
  1381. #ifdef SIGNED_COMPARE_SLOW
  1382.         fprintf(stderr, "SIGNED_COMPARE_SLOW, ");
  1383. #endif
  1384. #ifdef XENIX_16
  1385.         fprintf(stderr, "XENIX_16, ");
  1386. #endif
  1387. #ifdef COMPATIBLE
  1388.         fprintf(stderr, "COMPATIBLE, ");
  1389. #endif
  1390. #ifdef DEBUG
  1391.         fprintf(stderr, "DEBUG, ");
  1392. #endif
  1393. #ifdef BSD4_2
  1394.         fprintf(stderr, "BSD4_2, ");
  1395. #endif
  1396.         fprintf(stderr, "BITS = %d\n", BITS);
  1397. }
  1398.  
  1399.